package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class HeBeiService implements CrawlerScript {


    @Autowired
    private ChromeBrowser chromeBrowser;


    @Autowired
    private SaveDataUtil saveDataUtil;

    private static final Logger log = LoggerFactory.getLogger(HeBeiService.class);

    private static final String province = "河北";

    @Override
    public void start() {
        ChromeDriver driver = chromeBrowser.getChromeDriver();
        for (int i = 1; i < 14; i++) {

            try {
                driver.get("http://121.28.49.84:8003");
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                //clickRightLine(driver);
                String Xpath = "//*[@id='tvsite']/table[" + i + "]/tbody/tr/td[3]/a";
                driver.findElementByXPath(Xpath).click();
                List<WebElement> webElementList;
                if (i == 1) {
                    webElementList = driver.findElementsByCssSelector("#tvsite > div").get(0).findElements(By.cssSelector("table tbody > tr > td:nth-child(4)"));

                } else {
                    webElementList = driver.findElementsByCssSelector("#tvsite > div").get(1).findElements(By.cssSelector("table tbody > tr > td:nth-child(4)"));

                }
                for (int j = 0; j < webElementList.size(); j++) {
                    if (i == 1) {
                        webElementList = driver.findElementsByCssSelector("#tvsite > div").get(0).findElements(By.cssSelector("table tbody > tr > td:nth-child(4)"));

                    } else {
                        webElementList = driver.findElementsByCssSelector("#tvsite > div").get(1).findElements(By.cssSelector("table tbody > tr > td:nth-child(4)"));

                    }
                    // webElementList = driver.findElementsByCssSelector("#tvsite > div >table > tbody > tr > td:nth-child(4)");
                    webElementList.get(j).click();
                    log.info("第{}个市,第{}家企业开始", i, j);
                    Thread.sleep(3000);
                    driver.findElementByCssSelector("#navigation > li:nth-child(1) > a").click();
                    String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                    Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                    Elements allElements = parse.getAllElements();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("entName", allElements.select("#tbenpinfo > tbody > tr:nth-child(1) > td:nth-child(2)").text());
                    jsonObject.put("industry", allElements.select("#tbenpinfo > tbody > tr:nth-child(2) > td:nth-child(4)").text());
                    jsonObject.put("type", allElements.select("#tbenpinfo > tbody > tr:nth-child(3) > td:nth-child(6)").text());
                    jsonObject.put("address", allElements.select("#tbenpinfo > tbody > tr:nth-child(7) > td:nth-child(2)").text());

                    driver.findElementByCssSelector("#navigation > li:nth-child(2)").click();
                    List<MonitorData> monitorDataList = new ArrayList<>();
                    partClickNext(driver, monitorDataList, jsonObject, null);
                    saveDataUtil.saveTag(monitorDataList, province);
                }

            } catch (Exception e) {
                log.error("超时--{}", e.getMessage());
                continue;
            }

        }
        driver.quit();

    }

    private void partClickNext(ChromeDriver driver, List<MonitorData> monitorDataList, JSONObject jsonObject, String html) {


        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());

        Elements allElements = parse.getAllElements();
        Elements elements = allElements.select("#tbdata_auto > tbody > tr:nth-child(n+3)");


        if (!elements.text().equals("您查询的数据不存在！") && !elements.isEmpty()) {
            if (html == null) {
                try {
                    driver.findElementByCssSelector("#Asp_AutoData > table > tbody > tr > td:nth-child(2) > a:nth-child(1)").click();
                    Thread.sleep(3000);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
            html = htmlNew;
            for (Element e : elements) {
                MonitorData monitorData = new MonitorData();
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setCompanyName(jsonObject.getString("entName"));
                monitorData.setProvince(province);
                monitorData.setPollutionType(jsonObject.getString("type"));
                monitorData.setAddress(jsonObject.getString("address"));
                monitorData.setIndustry(jsonObject.getString("industry"));
                monitorData.setMonitorTime(e.getElementsByTag("td").get(1).text());
                monitorData.setMonitorInfo(e.getElementsByTag("td").get(2).text());
                monitorData.setMonitorPoint(e.getElementsByTag("td").get(3).text());
                monitorData.setMonitorValue(e.getElementsByTag("td").get(4).text());
                monitorData.setMonitorStandardValue(e.getElementsByTag("td").get(7).text());
                monitorData.setOverproof(e.getElementsByTag("td").get(8).text());
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);
            }
            try {
                if (!allElements.select("#Asp_AutoData > table > tbody > tr > td:nth-child(2) > a:nth-child(3)").attr("disabled").isEmpty()) {
                    log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                    return;
                }
                driver.findElementByCssSelector("#Asp_AutoData > table > tbody > tr > td:nth-child(2) > a:nth-child(3)").click();
                Thread.sleep(5000);
                partClickNext(driver, monitorDataList, jsonObject, html);
            } catch (Exception e) {
                log.error(e.getMessage());
                return;
            }

        }
    }


}
